import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class ApiService {
    private headers = new Headers({'Content-Type': 'application/json'});
    // header = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
    private url = 'http://my.com/1.php';// Test
    // private url = 'http://my.com/1.php';// 正式

    constructor(private http: Http) {
    }

    /**
     * http POST
     * @param url
     * @param data
     */
    httpPost(url: string, data: Object): Promise<Object> {
        return this.http.post(url, data, {headers: this.headers})
            .toPromise()
            .then(res => res.json().data as Object)
            .catch(this.handleError);
    }

    /**
     * HTTP GET
     * @param url
     * @param data
     */
    httpGet(url, data: Object): Promise<Object> {
        return this.http.get(url)
            .toPromise()
            .then(res => res.json().data as Object)
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }

    /**
     * 返回url
     * @param key
     */
    private getUrl(key: string = ''): string {
        if (key = '') {
            return this.url;
        }
        let postUrl = {
            'login': 'auth/login',
            'logout': 'auth/logout'
        };
        if (postUrl[key] != undefined) {
            return this.url + postUrl[key];
        }
        return '';
    }
}
